package main

import (
	"RDSPostgreSQL/common"
	"database/sql"
	"fmt"
	"github.com/pkg/errors"
	"log"
	"time"
)

type u struct {
	id          int
	user_name   string
	create_time time.Time
}

func checkError(err error) {
	if err != nil {
		log.Printf("%+v", err)
	}
}

func main() {
	db := common.GetDb()
	defer db.Close()
	//插入数据
	err := insert(db)
	if err != nil {
		log.Printf("%+v", err)
		return
	}
	//更新数据
	err = update(db)
	if err != nil {
		log.Printf("%+v", err)
		return
	}
	//删除数据
	err = delete(db)
	if err != nil {
		log.Printf("%+v", err)
		return
	}
	//查询数据
	err = query(db)
	if err != nil {
		log.Printf("%+v", err)
		return
	}
}

//插入数据
func insert(db *sql.DB) error {
	stmt, err := db.Prepare("INSERT INTO user(user_name,create_time) VALUES($1,$2)")
	if err != nil {
		return errors.Wrap(err, "ERR: fail to prepare")
	}

	res, err := stmt.Exec("ah", time.Now())
	if err != nil {
		return errors.Wrap(err, "ERR: fail to insert")
	}
	fmt.Printf("res = %d", res)
	return nil
}

//更新数据
func update(db *sql.DB) error {
	stmt, err := db.Prepare("update user set user_name=$1 WHERE u_id=$2")
	if err != nil {
		return errors.Wrap(err, "ERR: fail to prepare")
	}
	res, err := stmt.Exec("zhangsan", 1)
	if err != nil {
		return errors.Wrap(err, "ERR: fail to update")
	}
	fmt.Printf("res = %d", res)
	return nil
}

//删除数据
func delete(db *sql.DB) error {
	stmt, err := db.Prepare("delete from user where user_name=$1")
	if err != nil {
		return errors.Wrap(err, "ERR: fail to prepare")
	}
	res, err := stmt.Exec("zhangsan")
	if err != nil {
		return errors.Wrap(err, "ERR: fail to delete")
	}
	fmt.Printf("res = %d", res)
	return nil
}

func query(db *sql.DB) error {
	rows, err := db.Query("select u_id, user_name, create_time from user where user_name=$1", "ah")
	if err != nil {
		return errors.Wrap(err, "ERR: fail to query")
	}
	//延迟关闭rows
	defer rows.Close()

	for rows.Next() {
		user := u{}
		err := rows.Scan(&user.id, &user.user_name, &user.create_time)
		if err != nil {
			return errors.Wrap(err, "ERR: fail to scan")
		}
		fmt.Printf("id = %v, name = %v, time = %v\n", user.id, user.user_name, user.create_time)
	}
	return nil
}
